package com.bilibili.juc.threadPool;

import java.util.concurrent.*;

/**
 * @author zuife
 * @description、 创建线程的方式 使用线程池
 * @since 2024-04-20 21:55:36
 */
public class ThreadPoolDemo {
    public static void main(String[] args) {
        /**
         * 指定线程数量的线程池
         */
        ExecutorService service = Executors.newFixedThreadPool(10);
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        //设置线程池的属性
        System.out.println(service.getClass());
        service1.setCorePoolSize(15);
        service1.setMaximumPoolSize(200);
        service1.setKeepAliveTime(2, TimeUnit.DAYS);
        service1.setThreadFactory( new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                return null;
            }
        });
        service1.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        /**
         * 指定的线程操作，需要提供实现Runnable接口或Callable接口实现类的对象
         */
        service.execute(new NumberThread());
        service.execute(new NumberThread1());
//        service.submit(new Callable<String>() {
//            @Override
//            public String call() throws Exception {
//                return null;
//            }
//        });
        //3.关闭线程池
        service.shutdown();
    }
}

class NumberThread implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

class NumberThread1 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 1) {
                System.out.println(Thread.currentThread().getName() + ":" + i);
            }
        }
    }
}

